package com.claude.mainactivity;

import java.util.ArrayList;
import java.util.Iterator;

import org.json.JSONObject;

import com.android.volley.VolleyError;
import com.claude.bean.Cron;
import com.claude.bean.Session;
import com.claude.bean.Student;
import com.claude.bean.Subject;
import com.claude.communication.RequestManager;
import com.claude.communication.RequestNode;
import com.claude.communication.RequestNode.RequestListener;
import com.claude.sql.LessionTableManager;
import com.claude.sql.SQLManager;
import com.claude.sql.SessionTableManager;
import com.claude.sql.StudentTableManager;
import com.claude.sql.TmpCheckTableManager;
import com.claude.sql.TmpCheckTeaTableManager;
import com.claude.ui.CheckCompanet;
import com.claude.ui.CheckCompanet.MessageItem;
import com.claude.ui.ListViewCompat;
import com.claude.ui.CheckCompanet.DeleteHolderListener;
import com.claude.ui.SlideView;
import com.claude.ui.SlideView.OnSliderListener;
import com.claude.util.Configure;
import com.claude.util.Parser;
import com.claude.util.QueryParser;
import com.claude.util.TimeTool;
import com.special.ResideMenuDemo.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class CheckStudentActivity extends Activity {

	final private int REQUEST_STUDENT = 1;
	private ListView mListView = null;
	private ArrayList<Student> mArrayListStudent = null;
	private RequestListener mRequestListener = null;
	private RequestManager mRequestManager = null;
	private Configure configure = null;
	private MyApplication mMyApplication = null;
	private ProgressDialog mProgressDialog = null;
	private Cron mCron = null;
	private SQLiteDatabase mSQLiteDatabase = null;
	private SessionTableManager mSessionTableManager = null;
	private LessionTableManager mLessionTableManager = null;
	private StudentTableManager mStudentTableManager = null;
	private Session mSession = null;
	private Subject mSubject = null;
	private CheckCompanet mCheckCompanet = null;
	private OnSliderListener mOnSliderListener = null;
	private DeleteHolderListener mDeleteHolderListener = null;
	private SlideView mLastSlideViewWithStatusOn = null;
	private TextView mTextView = null;
	private Button mTestBtn = null;

	private String mSequenceId = null;
	private TmpCheckTeaTableManager mTmpCheckTeaTableManager = null;
	private TmpCheckTableManager mTmpCheckTableManager = null;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_check_student);
		configure = Configure.getInstance();
		mMyApplication = (MyApplication) getApplication();
		mTextView = (TextView) findViewById(R.id.tx);
		mSession = mMyApplication.getCurSession();
		mSubject = mMyApplication.getCurSubject();
		mTestBtn = (Button) findViewById(R.id.btn);
		mTestBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				inputMethodManager.toggleSoftInput(0,
						InputMethodManager.SHOW_FORCED);
			}
		});
	}

	public void onResume() {
		if (mMyApplication.getCheckState() == null) {
			if (mMyApplication.getOfflineState()) {
				showDialog();
				this.getResource();
			} else {
				this.initResource();
			}
		} else {
			mOnSliderListener = new MyOnSliderListener();
			mDeleteHolderListener = new MyDeleteHolderListener();
			mCheckCompanet = new CheckCompanet(this,
					mMyApplication.getCheckState(), mOnSliderListener,
					mDeleteHolderListener, 1);
			mListView = (ListViewCompat) findViewById(R.id.listview);
			mListView.setAdapter(mCheckCompanet.getAdapter());
			mArrayListStudent = mMyApplication.getStudents();
		}
		SQLManager sqlManager = new SQLManager(this);
		mSQLiteDatabase = sqlManager.getWritableDatabase();
		mLessionTableManager = new LessionTableManager(mSQLiteDatabase);
		mSessionTableManager = new SessionTableManager(mSQLiteDatabase);
		mStudentTableManager = new StudentTableManager(mSQLiteDatabase);
		super.onResume();
	}

	public void onStop() {
		super.onStop();
		if (mRequestManager != null) {
			mRequestManager.stopRequest();
		}
		this.finish();
	}

	public boolean onKeyDown(int key_code, KeyEvent event) {
		if (key_code == KeyEvent.KEYCODE_BACK) {
			quitCheckStudent();
			return true;
		}
		if (key_code == KeyEvent.KEYCODE_VOLUME_DOWN) {
			return true;
		}
		if (key_code == KeyEvent.KEYCODE_VOLUME_UP) {
			return true;
		}
		if (key_code == KeyEvent.KEYCODE_VOLUME_MUTE) {
			return true;
		}
		if (key_code == KeyEvent.KEYCODE_MENU) {
			return false;
		}
		if (key_code == KeyEvent.KEYCODE_FOCUS) {
			return false;
		}
		if (key_code == KeyEvent.KEYCODE_CAMERA) {
			return false;
		}
		mTextView.setText(mTextView.getText()
				+ String.valueOf((char) event.getUnicodeChar()));
		String id = mTextView.getText().toString();
		if (id.length() == 10) {
			mTextView.setText("");
			id = id.replace("\n", "");
			id = stringswap(id);
			Long idcard = Long.parseLong(id, 16);
			id = Long.toString(idcard);
			checkStudent(id);
			return super.onKeyDown(key_code, event);
		}
		return false;
	}

	private void showDialog() {
		mProgressDialog = new ProgressDialog(CheckStudentActivity.this);
		mProgressDialog.setCanceledOnTouchOutside(false);
		mProgressDialog.show();
	}

	private void initResource() {
		if (mSQLiteDatabase == null) {
			mSQLiteDatabase = new SQLManager(CheckStudentActivity.this)
					.getReadableDatabase();
			if (mStudentTableManager == null) {
				mStudentTableManager = new StudentTableManager(mSQLiteDatabase);
			}
		}
		Cursor cursor = mStudentTableManager
				.search(mSession.getSessionNumber());
		mArrayListStudent = QueryParser.getStudents(cursor);
		mCron = mMyApplication.getCron();
		initView();
		mMyApplication.setCheckState(mCheckCompanet.getData());
	}

	private void getResource() {
		mRequestListener = new MyRequestListener();
		mRequestManager = RequestManager.newInstance();
		RequestNode requestNode = new RequestNode(getParamsStudent(),
				mRequestListener, null, REQUEST_STUDENT);
		mRequestManager.addRequest(requestNode);
		mRequestManager.startRequest();
	}

	private String getParamsStudent() {
		return String.format(configure.getSessionUrl()
				+ "?teacherNumber=%s&sessionNumber=%s", mMyApplication
				.getUser().getTeacherNumber(), mMyApplication.getCurSession()
				.getSessionNumber());
	}

	private void initView() {
		mOnSliderListener = new MyOnSliderListener();
		mDeleteHolderListener = new MyDeleteHolderListener();
		mCheckCompanet = new CheckCompanet(this, mArrayListStudent,
				mOnSliderListener, mDeleteHolderListener);
		mListView = (ListViewCompat) findViewById(R.id.listview);
		mListView.setAdapter(mCheckCompanet.getAdapter());
		mMyApplication.setStudents(mArrayListStudent);
		mSequenceId = this.getSequenceNum(TimeTool.getDate().toString(), mCron
				.getStartTime(), mMyApplication.getUser().getTeacherNumber(),
				mMyApplication.getCurSession().getSessionNumber());

		// insert the teacher check information
		//TODO
		if(mSQLiteDatabase != null){
			if(!mSQLiteDatabase.isOpen()){
				mSQLiteDatabase = new SQLManager(CheckStudentActivity.this).getWritableDatabase();
			}
		}else{
			mSQLiteDatabase = new SQLManager(CheckStudentActivity.this).getWritableDatabase();
		}
		mTmpCheckTeaTableManager = new TmpCheckTeaTableManager(mSQLiteDatabase);
		mTmpCheckTeaTableManager.insert(mSequenceId, mMyApplication.getUser()
				.getTeacherNumber(), TimeTool.getTime().toString(), null, null,
				"0");
		mTmpCheckTableManager = new TmpCheckTableManager(mSQLiteDatabase);
	}

	private void insertValues() {
		mLessionTableManager.insert(mCron.getLessonNumber(),
				mCron.getStartTime(), String.valueOf(TimeTool.getWeek()));
		mSessionTableManager.insert(mSession.getSessionNumber(),
				mSession.getClassName(), mSubject.getSubjectNumber(),
				mCron.getLessonNumber());
		Iterator<Student> iterator = mArrayListStudent.iterator();
		while (iterator.hasNext()) {
			Student student = iterator.next();
			mStudentTableManager.insert(student.getStudentNumber(),
					student.getName(), student.getCardMac(),
					mSession.getSessionNumber(), student.getSex());
		}
		mSQLiteDatabase.close();
	}

	class MyRequestListener implements RequestListener {
		public void onSuccess(JSONObject jsonObject, int tag) {
			mArrayListStudent = Parser.getStudent(jsonObject);
			mCron = Parser.getCron(jsonObject);
			if (mCron != null) {
				mMyApplication.setCron(mCron);
			} else {
			}
			if (mArrayListStudent != null) {
				insertValues();
				mProgressDialog.dismiss();
				initView();
				mMyApplication.setCheckState(mCheckCompanet.getData());
			} else {
				mProgressDialog.dismiss();
			}
		}

		public void onError(VolleyError volleyError, int tag) {
			Toast.makeText(CheckStudentActivity.this, "网络环境不佳请重试",
					Toast.LENGTH_LONG).show();
			mProgressDialog.dismiss();
			gotoBack();
		}
	}

	private void gotoBack() {
		Intent intent = new Intent();
		intent.setClass(CheckStudentActivity.this, ClassSelectActivity.class);
		CheckStudentActivity.this.startActivity(intent);
	}

	/**
	 * 
	 * @param date
	 *            class date
	 * @param time
	 *            class start time
	 * @param teacherid
	 *            teacher's id
	 * @param sessionid
	 *            class's session id
	 * @return sequence number which ensure only one session
	 */
	private String getSequenceNum(String date, String time, String teacherid,
			String sessionid) {
		String[] datesequence = date.toString().split("-");
		char[] tmp = datesequence[0].toCharArray();
		String sum = "" + tmp[2] + tmp[3] + datesequence[1] + datesequence[2];
		String[] timesequence = time.split(":");
		return sum + timesequence[0] + timesequence[1] + teacherid + sessionid;
	}

	/**
	 * 
	 * @param str
	 *            the data which readed by OTG device
	 * @return swap the string by bit
	 */
	public String stringswap(String string) {
		Long tmp = Long.valueOf(string);
		String tmpStr = Long.toHexString(tmp);
		int i = 0;
		if (tmpStr.length() < 8) {
			for (i = 7 - tmpStr.length(); i >= 0; i--)
				tmpStr = "0" + tmpStr;
		}
		char charSquence[] = tmpStr.toCharArray();
		String result = String.valueOf(charSquence[6])
				+ String.valueOf(charSquence[7])
				+ String.valueOf(charSquence[4])
				+ String.valueOf(charSquence[5])
				+ String.valueOf(charSquence[2])
				+ String.valueOf(charSquence[3])
				+ String.valueOf(charSquence[0])
				+ String.valueOf(charSquence[1]);
		return result;
	}

	private void checkStudent(String cardMac) {
		boolean tag = false;
		ArrayList<MessageItem> temp = mMyApplication.getCheckState();
		int index = 0;
		while (index != temp.size()) {
			MessageItem tmp = temp.get(index);
			if (tmp.cardMac.equals(cardMac)) {
				Toast.makeText(CheckStudentActivity.this,
						String.format("%s考勤成功", temp.get(index).title), 1000)
						.show();
				mTmpCheckTableManager.insert(mSequenceId, tmp.time, "正常考勤", TimeTool.getTime().toString(), TimeTool.getDate().toString(), cardMac);
				mMyApplication.getCheckState().remove(index);
				temp.remove(index);
				mCheckCompanet.getAdapter().removeItem(index);
				tag = true;
			}
			index++;
		}
		if (tag == false) {
			index = 0;
			while (index != mArrayListStudent.size()) {
				if (mArrayListStudent.get(index).getCardMac().equals(cardMac)) {
					break;
				}
				index++;
			}
			if (index != mArrayListStudent.size()) {
				Toast.makeText(
						CheckStudentActivity.this,
						String.format("%s,请不要重复刷卡", mArrayListStudent
								.get(index).getName()), 1000).show();
			} else {
				// new card
				// TODO
				jumpToInitNewCard(cardMac);
			}
		}
	}

	void jumpToInitNewCard(String cardMac) {
		Intent intent = new Intent();
		intent.putExtra("cardMac", cardMac);
		intent.setClass(CheckStudentActivity.this, InitNewCardActivity.class);
		CheckStudentActivity.this.startActivity(intent);
	}

	void quitCheckStudent() {
		new AlertDialog.Builder(CheckStudentActivity.this)
				.setMessage("退出考勤信息会丢失，确定退出？")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						mMyApplication.setCheckState(null);
						mTmpCheckTeaTableManager.delete(mSequenceId, mMyApplication.getUser().getTeacherNumber());
						gotoBack();
					}
				}).setNegativeButton("取消", null).create().show();
	}

	class MyOnSliderListener implements OnSliderListener {
		public void onSlider(View view, int status) {
			if (mLastSlideViewWithStatusOn != null
					&& mLastSlideViewWithStatusOn != view) {
				mLastSlideViewWithStatusOn.shrink();
			}
			if (status == SLIDE_STATUS_ON) {
				mLastSlideViewWithStatusOn = (SlideView) view;
			}
		}
	}

	class MyDeleteHolderListener implements DeleteHolderListener {
		public void onDelete(int position, View convertView, ViewGroup parent,
				View v) {
		}
	}
}
